package worldinruin.gui.imp.gameview;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.WindowConstants;

import worldinruin.core.imp.battle.Dice;
import worldinruin.utils.IObservable;

public class DiceLabel extends JLabel implements PropertyChangeListener {
	
	private IObservable dice;
	private int numberOfSpots = 6;
	private Graphics g;
	
	private final int SIDE = 50;
	private final int SPOT_DIAMETER = SIDE / 5;	
	private final int GAP_LENGTH = (SIDE - 3 * SPOT_DIAMETER) / 4;	
	private final int LEFT = 0;
	private final int TOP = 0;
	private final int MIDDLE = 1;
	private final int BOTTOM = 2;
	private final int RIGHT = 2;
	

	public static void main(String[] args){
		JFrame fr = new JFrame();
		fr.setLayout(new GridLayout(1,1));
		Dice dice = new Dice();
		fr.add(new DiceLabel(dice));
		fr.pack();
		fr.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
		fr.setLocationRelativeTo(null);
		fr.setVisible(true);
		dice.roll();

		
	}
	
	/**
	 * Creates a viewable dice.
	 * @param dice Type of dice.
	 */
	public DiceLabel(Dice dice){
		this.dice = dice;
		dice.addPropertyChangeListener(this);
		setPreferredSize(new Dimension(SIDE, SIDE));
		setBackground(Color.white);
		setOpaque(true);
	}

	@Override
	public void propertyChange(PropertyChangeEvent e) {
		numberOfSpots = (Integer) e.getNewValue();
		repaint();
	}
	
	@Override
	public void paintComponent(Graphics g){
		this.g = g;
		g.setColor(Color.white);
		g.fillRect(0, 0, SIDE, SIDE);
		g.setColor(Color.black);
		drawSpots(numberOfSpots);
		g.drawRect(0, 0, SIDE, SIDE);
	}
	
	/**
	 * Draws the dots on the dice.
	 * @param numberOfSpots
	 */
	private void drawSpots(int numberOfSpots){
			
			switch(numberOfSpots){
			
			case 1:
				drawSpot(MIDDLE, MIDDLE);
				break;			
				
			case 2:
				drawSpot(LEFT, TOP);
				drawSpot(RIGHT, BOTTOM);
				break;
				
			case 3:
				drawSpots(1);
				drawSpots(2);
				break;
				
			case 4:
				drawSpots(2);
				drawSpot(LEFT, BOTTOM);
				drawSpot(RIGHT, TOP);
				break;			
				
			case 5:
				drawSpots(1);
				drawSpots(4);
				break;
				
			case 6:
				drawSpots(4);
				drawSpot(LEFT, MIDDLE);
				drawSpot(RIGHT, MIDDLE);
				break;
				
			}
		
		}
	
	/**
	 * Draws dot.
	 * @param x x-coordinate.
	 * @param y y-coordinate.
	 */
	private void drawSpot(int x, int y){
		g.fillOval(x * SPOT_DIAMETER + (x + 1) * GAP_LENGTH, y * SPOT_DIAMETER +
				(y + 1) * GAP_LENGTH, SPOT_DIAMETER, SPOT_DIAMETER);
	}
	
	
	


}
